package com.huluobo.kotlinim1911a.ui.activity

import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.huluobo.kotlinim1911a.R
import com.huluobo.kotlinim1911a.adapter.EMMessageListenerAdapter
import com.huluobo.kotlinim1911a.adapter.MessageListAdapter
import com.huluobo.kotlinim1911a.base.BaseActivity
import com.huluobo.kotlinim1911a.contract.chat.ChatContract
import com.huluobo.kotlinim1911a.contract.chat.ChatPresenter
import com.hyphenate.EMMessageListener
import com.hyphenate.chat.EMClient
import com.hyphenate.chat.EMMessage
import kotlinx.android.synthetic.main.activity_chat.*
import kotlinx.android.synthetic.main.header.*

/**
 * Created by lc on 2022/6/28.
 */
class ChatActivity : BaseActivity(), ChatContract.View {
    val presenter = ChatPresenter(this)
    lateinit var username: String

    private val messageListener = object : EMMessageListenerAdapter() {
        override fun onMessageReceived(messages: MutableList<EMMessage>?) {
            presenter.addMessage(username, messages)
            runOnUiThread {
                recyclerView.adapter?.notifyDataSetChanged()
                scrollToBottom()
            }
        }
    }

    private fun scrollToBottom() {
        recyclerView.scrollToPosition(presenter.messages.size - 1)
    }

    override fun getLayoutResId(): Int = R.layout.activity_chat
    override fun init() {
        super.init()
        initHeader()
        initEditText()
        initRecyclerView()

        send.setOnClickListener { send() }
        edit.setOnEditorActionListener { _, _, _ ->
            send()
            true
        }

        EMClient.getInstance().chatManager().addMessageListener(messageListener)
        presenter.loadMessages(username)
    }

    private fun send() {
        hideSoftKeyboard()
        val message = edit.text.trim().toString()
        presenter.sendMessage(username, message)
    }

    private fun initRecyclerView() {
        recyclerView.apply {
            setHasFixedSize(true)
            layoutManager = LinearLayoutManager(context)
            adapter = MessageListAdapter(context, presenter.messages)

            addOnScrollListener(object : RecyclerView.OnScrollListener() {
                override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                    //当Recyclerview是一个空闲的状态的时候,检查是否滑动到顶部
                    if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                        //如果第一个可见的条目(Item)的位置是0,为滑动到顶部
                        val linearLayoutManager = layoutManager as LinearLayoutManager
                        if (linearLayoutManager.findFirstVisibleItemPosition() == 0) {
                            presenter.loadMoreMessage(username)
                        }
                    }
                }
            })

        }
    }

    private fun initEditText() {
        edit.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                //如果用户输入的文本长度大于0,发送按钮开启
                send.isEnabled = !s.isNullOrEmpty()
            }

        })
    }

    private fun initHeader() {
        back.visibility = View.VISIBLE
        back.setOnClickListener { finish() }

        //获取聊天的用户名
        val userName = intent.getStringExtra("username")
        username = userName
        val titleString = String.format(getString(R.string.chat_title), userName)
        headerTitle.text = titleString
    }

    override fun onStartSendMessage() {
        //为了展示发送的进度条而刷新
        recyclerView.adapter?.notifyDataSetChanged()
    }

    override fun onSendMessageSuccess() {
        //为了展示发送消息的item而刷新
        recyclerView.adapter?.notifyDataSetChanged()
        edit.text.clear()
        scrollToBottom()
    }

    override fun onSendMessageFailed() {
        //为了展示发送消息失败的小叹号
        recyclerView.adapter?.notifyDataSetChanged()
    }

    override fun onMessagesLoaded() {
        recyclerView.adapter?.notifyDataSetChanged()
        scrollToBottom()
    }

    override fun onMoreMessagesLoaded(size: Int) {
        recyclerView.adapter?.notifyDataSetChanged()
        recyclerView.scrollToPosition(size)
    }

    override fun onDestroy() {
        super.onDestroy()
        EMClient.getInstance().chatManager().removeMessageListener(messageListener)
    }
}